package selectionweb.web.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import selectionweb.web.Course;
import selectionweb.web.Student;
import selectionweb.web.repository.StudentRepository;

import javax.validation.Valid;
import java.io.*;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/personalInformation")
@SessionAttributes("course")
public class PersonalInformationController {
    private StudentRepository studentRepository;

    @Autowired
    public PersonalInformationController(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    @ModelAttribute(name = "course")
    public Course course(){
        return new Course();
    }

    @ModelAttribute(name = "student")
    public Student student(){return new Student();}


    @GetMapping
    public String personalInformation(Model model) {
        model.addAttribute("student", new Student());
        return "personalInformation";
    }
    @PostMapping
    public String processOrder  (@Valid Student student,Errors errors,@ModelAttribute Course course)
    {
        if (errors.hasErrors()) {
            return "personalInformation";
        }

        Student saved=studentRepository.save(student);
        course.addDesign(saved);
        return "redirect:/selection";
    }
}
